﻿using DiscussProject.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DiscussProject.Controllers
{
    public class UserController : Controller
    {
        // GET: User
        public ActionResult Index()
        {
            OutputMsg("index_ret");
            int uid = (int)Session["Id"];
            ArticleContext db = new ArticleContext();
            var result = from item in db.Articles where item.UserId == uid select item;
            ViewData["articles"] = result.ToArray();
            return View();
        }
        

        [AllowAnonymous]
        [HttpPost]
        public ActionResult RegisterMethod(User user)
        {
            if (ModelState.IsValid)
            {
                if (UserMapper.QueryUserByEmail(user.Email) != null)
                {
                    TempData["login_ret"] = "该邮箱已被注册!";
                }
                else
                {
                    UserMapper.InsertUser(user);
                }
            }
            else TempData["login_ret"] = "注册信息不合法!";
            return RedirectToAction("Login", "User");
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult LoginMethod(string email, string pwd)
        {
            var user = UserMapper.QueryUserByEmail(email);
            if (user == null || user.Password != pwd)
            {
                TempData["login_ret"] = "用户名或密码错误!";
                return RedirectToAction("Login", "User");
            }
            Session["Id"] = user.Id;
            Session["Name"] = user.Name;
            if (user.Picture == null || user.Picture == "") user.Picture = "https://tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg";
            Session["head_img"] = user.Picture;
            return RedirectToAction("Index", "User");
        }

        [HttpPost]
        public ActionResult UploadImage()
        {
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase img = Request.Files["head_photo"];
                string fileType = Path.GetExtension(img.FileName);//获取扩展名
                string serverPath = Server.MapPath("~/Images/");
                //看看文件夹是否存在
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);
                }
                if (fileType == null)
                {
                    TempData["set_ret"] = "请检查上传的文件是否正常!";
                    return RedirectToAction("Set", "User");
                }
                fileType = fileType.ToLower();
                if ("(.gif)|(.jpg)|(.bmp)|(.jpeg)|(.png)".Contains(fileType))
                {
                    //生成一个随机值 避免命名冲突；
                    string fileName = System.Guid.NewGuid().ToString();
                    fileName += fileType;
                    img.SaveAs(serverPath + fileName);
                    //获取当前usr 并将头像URL存入数据库
                    var usr = UserMapper.QueryUserByUid((int)Session["Id"]);
                    usr.Picture = "../Images/" + fileName;
                    Session["head_img"] = usr.Picture;
                    UserMapper.UpdateUser(usr);
                    return RedirectToAction("Index", "User");
                }
                else
                {
                    TempData["set_ret"] = "只支持上传图片!";
                    return RedirectToAction("Set", "User");
                }
            }
            TempData["set_ret"] = "上传的图片不能为空!";
            return RedirectToAction("Set", "User");
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult ResetPassword(string email,string pwd)
        {
            if (email == null || pwd == null || pwd == "" || email == "")
            {
                TempData["login_ret"] = "账号或密码不为空!";
                return RedirectToAction("Login", "User");
            }
            var user = UserMapper.QueryUserByEmail(email);
            if (user == null)
            {
                TempData["login_ret"] = "该账号不存在!";
                return RedirectToAction("Login", "User");
            }
            user.Password = pwd;
            UserMapper.UpdateUser(user);
            return RedirectToAction("Login", "User");
        }

        public ActionResult ChangePwd(string oldPwd,string newPwd)
        {
            var user = UserMapper.QueryUserByUid((int)Session["id"]);
            if(user.Password != oldPwd)
            {
                TempData["set_ret"] = "旧密码错误!";
                return RedirectToAction("Set", "User");
            }
            user.Password = newPwd;
            UserMapper.UpdateUser(user);
            TempData["set_ret"] = "修改成功!";
            return RedirectToAction("Set", "User");
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }
        [AllowAnonymous]
        public ActionResult Forget()
        {
            return View();
        }

        public ActionResult Set()
        {
            OutputMsg("set_ret");
            return View();
        }

        [HttpPost]
        public ActionResult Update([Bind(Include = "Name,Address,Signature,Email,Gender")] User user)
        {
            var modifiedUser = UserMapper.QueryUserByEmail(user.Email);
            if (modifiedUser != null)
            {
                TempData["set_ret"] = "该邮箱已被注册!";
                return RedirectToAction("Set", "User");
            }
            //ok
            int uid = (int)Session["Id"];
            //昵称和邮箱必填 如果没有则不修改
            modifiedUser = UserMapper.QueryUserByUid(uid);
            modifiedUser.Name = (user.Name == null? modifiedUser.Name: user.Name);
            modifiedUser.Address = user.Address;
            modifiedUser.Signature = user.Signature;
            modifiedUser.Email = (user.Email == null ? modifiedUser.Email : user.Email);
            modifiedUser.Gender = user.Gender;
            UserMapper.UpdateUser(modifiedUser);

            return RedirectToAction("Home", "User");
        }

        

        public ActionResult Home()
        {
            var uid = (int)Session["Id"];
            var usr = UserMapper.QueryUserByUid(uid);
            var usrDto = new UserDto(usr);
            if (usrDto.Address == null || usrDto.Address == "") usrDto.Address = "不告诉你...";
            if (usrDto.Signature == null || usrDto.Signature == "") usrDto.Signature = "此用户很懒，还没留下签名...";
            ViewBag.usrDto = usrDto;
            return View();
        }

        [AllowAnonymous]
        public ActionResult Login()
        {
            OutputMsg("login_ret");
            return View();
        }

        private void OutputMsg(string key)
        {
            object alert = TempData[key];
            if (alert != null)
            {
                string msg = (string)alert;
                Response.Write("<script>alert('" + msg + "');</script>");
            }
        }
    }
}